'use client';

import { useState, useEffect, useRef } from 'react';
import dynamic from 'next/dynamic';
import { useMediaQuery } from '@/hooks/useMediaQuery';

// 动态导入 ReactPlayer 和 HLSPlayer 以避免 SSR 问题
const ReactPlayer = dynamic(() => import('react-player/lazy'), {
    ssr: false,
    loading: () => <LoadingPlayer />,
});

const HLSPlayer = dynamic(() => import('./HLSPlayer'), {
    ssr: false,
    loading: () => <LoadingPlayer />,
});

function LoadingPlayer() {
    return (
        <div className="aspect-video bg-gray-800 rounded-lg animate-pulse flex items-center justify-center">
            <span className="text-gray-400">加载播放器中...</span>
        </div>
    );
}

export default function VideoPlayer({
    url,
    title,
    isLive = true,
    onReady,
    onError,
    className = '',
}) {
    const playerRef = useRef(null);
    const [isPlaying, setIsPlaying] = useState(false);
    const [volume, setVolume] = useState(0.5);
    const [seeking, setSeeking] = useState(false);
    const [played, setPlayed] = useState(0);
    const [loaded, setLoaded] = useState(0);
    const [duration, setDuration] = useState(0);
    const [playbackRate, setPlaybackRate] = useState(1.0);
    const [isHLS, setIsHLS] = useState(false);

    const isMobile = useMediaQuery('(max-width: 768px)');
    const isTablet = useMediaQuery('(max-width: 1024px)');

    // 检测是否是 HLS 流
    useEffect(() => {
        setIsHLS(url?.toLowerCase().includes('.m3u8'));
    }, [url]);

    // 播放器配置
    const playerConfig = {
        file: {
            attributes: {
                crossOrigin: 'anonymous',
                controlsList: 'nodownload', // 禁用下载
            },
            forceHLS: true, // 强制使用 HLS
            forceVideo: true,
        },
        youtube: {
            playerVars: {
                modestbranding: 1,
                rel: 0,
            },
        },
    };

    // 播放器样式
    const playerStyles = {
        width: '100%',
        height: '100%',
        backgroundColor: '#000',
    };

    // 处理播放/暂停
    const handlePlayPause = () => {
        setIsPlaying(!isPlaying);
    };

    // 处理音量变化
    const handleVolumeChange = e => {
        setVolume(parseFloat(e.target.value));
    };

    // 处理进度变化
    const handleProgress = state => {
        if (!seeking) {
            setPlayed(state.played);
            setLoaded(state.loaded);
        }
    };

    // 处理播放速率变化
    const handlePlaybackRateChange = rate => {
        setPlaybackRate(rate);
    };

    // 处理错误
    const handleError = error => {
        console.error('播放器错误:', error);
        if (onError) onError(error);
    };

    return (
        <div className={`relative group ${className}`}>
            <div className="aspect-video bg-black rounded-lg overflow-hidden">
                {isHLS ? (
                    <HLSPlayer url={url} onReady={onReady} onError={handleError} />
                ) : (
                    <ReactPlayer
                        ref={playerRef}
                        url={url}
                        width="100%"
                        height="100%"
                        playing={isPlaying}
                        volume={volume}
                        playbackRate={playbackRate}
                        onReady={onReady}
                        onError={handleError}
                        onProgress={handleProgress}
                        onDuration={setDuration}
                        config={playerConfig}
                        style={playerStyles}
                        pip={!isMobile} // 画中画仅在非移动端启用
                        controls={true} // 使用原生控件
                        playsinline={true} // 在 iOS 中内联播放
                    />
                )}
            </div>

            {/* 自定义控件 - 仅在非移动端显示 */}
            {!isMobile && !isHLS && (
                <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 opacity-0 group-hover:opacity-100 transition-opacity">
                    <div className="flex items-center space-x-4">
                        <button
                            onClick={handlePlayPause}
                            className="text-white hover:text-gray-300"
                        >
                            {isPlaying ? '暂停' : '播放'}
                        </button>

                        <div className="flex items-center space-x-2">
                            <input
                                type="range"
                                min={0}
                                max={1}
                                step={0.1}
                                value={volume}
                                onChange={handleVolumeChange}
                                className="w-24"
                            />
                            <span className="text-white text-sm">{Math.round(volume * 100)}%</span>
                        </div>

                        {!isLive && (
                            <div className="flex items-center space-x-2">
                                <select
                                    value={playbackRate}
                                    onChange={e =>
                                        handlePlaybackRateChange(parseFloat(e.target.value))
                                    }
                                    className="bg-transparent text-white text-sm"
                                >
                                    {[0.5, 1, 1.5, 2].map(rate => (
                                        <option key={rate} value={rate}>
                                            {rate}x
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
